package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 0/1 * * * ?")  // 每分钟执行一次
    public void processTimeOutOrders(){
        log.info("定时处理超时订单:{}", LocalDateTime.now());
        /**
         * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
         */
        //查询 超过15分钟的待付款(1)订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT
                (Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        //遍历并处理
        if(ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                //更新订单状态为 6
                Orders ordersUpdate = Orders.builder()
                        .id(orders.getId())
                        .status(Orders.CANCELLED)
                        .cancelReason("订单超时，自动取消")
                        .cancelTime(LocalDateTime.now())
                        .build();
                orderMapper.update(ordersUpdate);
            }
        }
    }


    @Scheduled(cron = "0 0 1 * * ?")  //每天凌晨1点执行一次
    public void processDeliveryOrders() {

        log.info("定时处理状态为派送中的订单：{}", LocalDateTime.now());
        /**
         * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
         */
        //查询状态为派送中的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT
                (Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));

        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                //修改订单状态为已完成
                orders.setStatus(Orders.COMPLETED);

            }
        }

    }

}
